package objekte;

import javax.swing.*;
import java.awt.*;

public class Stampede extends JFrame{
  public static final int BREIT=20;
  public static final int HOCH=8;
  public static final char TIER='#';
  public static final char SPIELER='*';
  JTextArea anzeige;
  char[] herde;

  public Stampede(){
    herde=new char[BREIT*HOCH];
    for(int i=0; i<herde.length; ++i) herde[i]=' ';
    anzeige=new JTextArea(HOCH, BREIT);
    anzeige.setLineWrap(true);
    anzeige.setEditable(false);
    anzeige.setFont(new Font("Courier", Font.BOLD, 20));
    anzeige.setText(new String(herde));
    anzeige.setCaretPosition(BREIT/2);
    Container c=getContentPane();
    c.add(anzeige, BorderLayout.CENTER);
    pack();
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    new Takt(this, 500).start();
  }

  public boolean takt(){
    int pos=anzeige.getCaretPosition();
    pos=pos%BREIT;
    boolean collision=herde[pos+BREIT]==TIER;
    for(int i=BREIT; i<herde.length; ++i)
      herde[i-BREIT]=herde[i];
    herde[pos]=SPIELER;
    for(int i=herde.length-BREIT, n=i+BREIT; i<n; ++i)
      herde[i]=Math.random()<.3?TIER:' ';
    anzeige.setText(new String(herde));
    anzeige.setCaretPosition(pos);
    return !collision;
  }

  public void ende(){
    anzeige.setText("     GAME OVER");
  }

  public static void main(String[] args){
    new Stampede();
  }
}

class Takt extends Thread{
  Stampede stamp;
  int time;

  public Takt(Stampede s, int millis){
    stamp=s;
    time=millis;
  }

  public void run(){
    while(stamp.takt())
      try{
        Thread.sleep(time);
      } catch(InterruptedException ex){
        System.out.println(ex);
      }
    stamp.ende();
  }
}
